package com.supreme.secretserver.controller;

import com.alibaba.fastjson.JSONObject;
import com.supreme.commonboot.exception.BizException;
import com.supreme.commonboot.utils.AjaxResp;
import com.supreme.secretserver.annotation.Decrypt;
import com.supreme.secretserver.annotation.Encrypt;
import com.supreme.secretserver.props.EncryptProps;
import com.supreme.secretserver.secret.SecretParser;
import com.supreme.secretserver.utils.AESUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping(value = "secret")
public class SecretController {

    @Resource
    private EncryptProps encryptProps;

    @GetMapping(value = "encrypt")
    public AjaxResp encryptValue(@RequestParam(value = "message") String message) throws Exception {
        String encrypt = AESUtils.encrypt(message.getBytes(), encryptProps.getAesKeyBytes());
        System.out.println("encrypt = " + encrypt);
        return AjaxResp.instance(encrypt);
    }

    @PostMapping(value = "decrypt")
    public AjaxResp decryptValue(@RequestBody JSONObject bodyData) throws Exception {
        String message = bodyData.getString("message");
        if (StringUtils.isBlank(message)) {
            throw new BizException("message not found");
        }
        byte[] decrypt = AESUtils.decrypt(message.getBytes(), encryptProps.getAesKeyBytes());
        return AjaxResp.instance(new String(decrypt));
    }

    @Encrypt(type = SecretParser.AES)
    @GetMapping(value = "encryptTest")
    public AjaxResp encryptTest(@RequestParam(value = "message") String message) {
        final JSONObject jsonObject = new JSONObject() {{
            put("type", 99);
            put("message", message);
        }};
        return AjaxResp.instance(jsonObject);
    }

    @Decrypt(type = SecretParser.AES)
    @PostMapping(value = "decryptTest")
    public AjaxResp decryptTest(@RequestBody JSONObject bodyData) {
        return AjaxResp.instance(bodyData);
    }
}
